package cn.cw.gongjun.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by scorpio on 15/10/16.
 */
public class Tools {
    private static Toast toast;

    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }
    /**
     * 设置某个View的margin
     *
     * @param view   需要设置的view
     * @param left   左边距
     * @param right  右边距
     * @param top    上边距
     * @param bottom 下边距
     * @return
     */
    public static ViewGroup.LayoutParams setViewMargin(View view, int left, int right, int top, int bottom) {
        if (view == null) {
            return null;
        }

        int leftPx = left;
        int rightPx = right;
        int topPx = top;
        int bottomPx = bottom;
        ViewGroup.LayoutParams params = view.getLayoutParams();
        ViewGroup.MarginLayoutParams marginParams = null;
        //获取view的margin设置参数
        if (params instanceof ViewGroup.MarginLayoutParams) {
            marginParams = (ViewGroup.MarginLayoutParams) params;
        } else {
            //不存在时创建一个新的参数
            marginParams = new ViewGroup.MarginLayoutParams(params);
        }
        //设置margin
        marginParams.setMargins(leftPx, topPx, rightPx, bottomPx);
        view.setLayoutParams(marginParams);
        return marginParams;
    }
    /**
     * 显示对话框
     *
     * @param context
     * @param msg
     */
    public static void msgbox(Context context, String msg) {
        new AlertDialog.Builder((context)).setTitle("提示").setMessage(msg)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                    }
                }).show();
    }
    /**
     * 显示对话框,确认按钮处理
     *
     * @param context
     * @param msg
     */
    public static void msgbox(Context context, String title, String msg, String okButtonStr, DialogInterface.OnClickListener okClickListener) {
        new AlertDialog.Builder((context)).setTitle(title).setMessage(msg)
                .setPositiveButton(okButtonStr,okClickListener).show();
    }
    /**
     * 显示对话框,确认按钮处理 有取消
     *
     * @param context
     * @param msg
     */
    public static void msgbox2(Context context, String title, String msg, String okButtonStr, DialogInterface.OnClickListener okClickListener) {
        new AlertDialog.Builder((context)).setTitle(title).setMessage(msg).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        })
                .setPositiveButton(okButtonStr,okClickListener).show();
    }

    /*

     */
    public static void Log(String str){
        Log.e("TAG","-----------Err"+str);
    }

    /**
     * 获取手机的IMEI
     *
     * @param context
     * @return
     */
    public static String getIMEI1(Context context) {
        @SuppressLint("MissingPermission") String deviceId = ((TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE))
                .getDeviceId();
        return deviceId;
    }


    public static String getMacAddress(Context mContext) {
        String macStr = "";
        WifiManager wifiManager = (WifiManager) mContext
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo.getMacAddress() != null) {
            macStr = wifiInfo.getMacAddress();// MAC地址
        } else {
            macStr = "null";
        }

        return macStr;
    }

    /**
     * 判断null和""的情况
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str != null) {
            if (str.length() > 0) {
                return false;
            }
        }
        return true;
    }




    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, int dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, int pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }



    public static String currentVersion(Context context) {
        String ver = null;
        try {
            ver = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ver;
    }
    public static String currentVersionceshi(Context context, String appPackage) {
        String ver = null;
        try {
            appPackage = context.getPackageName();
            ver = context.getPackageManager().getPackageInfo(appPackage, 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ver;
    }
    /**
     * MD5 加密
     *
     * @param source
     * @return
     */
    public static String md5(String source) {
        StringBuffer sb = new StringBuffer(32);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(source.getBytes("utf-8"));
            for (int i = 0; i < array.length; i++) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
            }
        } catch (Exception e) {
            return null;
        }
        return sb.toString();
    }


    /**
     * 初始化申请权限 6.0
     */
    public static void requestPermission(Activity activity, String permission) {
        if (ContextCompat.checkSelfPermission(activity, permission) !=
                PackageManager.PERMISSION_GRANTED) {
//            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
//                // 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
//            } else {
            // 进行权限请求
            ActivityCompat.requestPermissions(activity, new String[]{permission}, 10);
//            }
        }
    }

    /**
     * 初始化申请权限 6.0 批量权限申请
     *
     * @param activity
     * @param permissions
     */
    public static void requestPermissions(final Activity activity, String[] permissions) {
        // 进行权限请求
        ActivityCompat.requestPermissions(activity, permissions, 10);
        int count = 0;
        for (int i = 0; i < permissions.length; i++) {
            final String permission = permissions[i];
            if (ContextCompat.checkSelfPermission(activity, permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                requestPermission(activity, permission);
            }

        }
    }

    /**
     * check if network avalable
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressLint("MissingPermission") NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();
            }
        }

        return false;
    }


    /**
     * 检测程序是否安装
     *
     * @param packageName
     * @return
     */
    private boolean isInstalled(Context mContext,String packageName) {
        PackageManager manager = mContext.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
        if (installedPackages != null) {
            for (PackageInfo info : installedPackages) {
                if (info.packageName.equals(packageName))
                    return true;
            }
        }
        return false;
    }

    /**
     * 权限 6.0 检测权限
     *
     * @param context
     * @param permissions
     * @return
     */
    public static boolean checkoutPermissions(final Context context, String[] permissions) {
        // 进行权限请求
        boolean result = true;
        int count = 0;
        for (int i = 0; i < permissions.length; i++) {
            final String permission = permissions[i];
            if (ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {
                count = count + 1;
            }
        }

        if (count == permissions.length) {
            result = true;
        } else {
            result = false;
        }
        return result;
    }

//    /*
//        权限判断 ，6.0 和5.0 都判断
//     */
//    public static int JudgementPermissions(final Context context, String permissions) {
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            int checkSelfPermission = ContextCompat.checkSelfPermission(context,permissions);
//            return checkSelfPermission;
//
//        }else {
//            int checkSelfPermission = PermissionChecker.checkSelfPermission(context, permissions);
//           return   checkSelfPermission;
//        }
//    }

    /**
     * 显示金额默认保留两位小数
     */
    public static String formatMoney(double money) {
        String result = String.format("%.2f", money);
        return result;
    }
    /**
     * 显示金额默认保留两位小数
     */
    public static double formatMoney2double(double money) {
        String result = String.format("%.2f", money);
        return Double.parseDouble(result);
    }
    /**
     * 规范时间格式
     */
    public static String formateTime(String time) {

        String[] t = time.split("\\(|\\)");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(Long.parseLong(t[1]));
    }

    /**
     * 规范日期
     *
     * @param date
     * @return
     */
    public static String formateDate(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(date);//定位时间
    }

    /**
     * 规范服务器获取的日期
     *
     * @param date
     * @return
     */
    public static String formateGetMonth(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        return df.format(date);//定位时间
    }

    /**
     * 判断String 是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }


    /**
     * 通过utf8 encode
     *
     * @param str
     * @return
     */
    public static String encodeUrlString(String str) {
        String s = str;
        try {
            s = URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(int year, int month, int day) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        String strData=year+"-"+month+"-"+day;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d=sdf.parse(strData);
//            Logs.Debug("------日期----"+d);
            cal.setTime(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
//        Logs.Debug("----------" + year+"年" + month+"月"+ day +"日"+ "==" + w);
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
    /*
    根据时间戳获得多久前
     */
    public static String getStandardDate(String timeStr) {
        String temp = "";
        try {
            long now = System.currentTimeMillis() / 1000;
            long publish = Long.parseLong(timeStr);
            long diff = now - publish;
            long months = diff / (60 * 60 * 24*30);
            long days = diff / (60 * 60 * 24);
            long hours = (diff - days * (60 * 60 * 24)) / (60 * 60);
            long minutes = (diff - days * (60 * 60 * 24) - hours * (60 * 60)) / 60;
            if (months > 0) {
                temp = months + "月前";
            } else if (days > 0) {
                temp = days + "天前";
            } else if (hours > 0) {
                temp = hours + "小时前";
            } else {
                temp = minutes + "分钟前";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp;
    }

    public static int getWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }


    /**
     * 检测网络是否有效
     *
     * @param context
     * @return ture 有网络
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            @SuppressLint("MissingPermission") NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /**
     * 返回当前屏幕是否为竖屏。
     *
     * @param context
     * @return 当且仅当当前屏幕为竖屏时返回true, 否则返回false。
     */
    public static boolean isScreenOriatationPortrait(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

//    /**
//     * @param context
//     * @return 返回平台数据
//     */
//    public static Object isDoubleSim(Context context) {
//        TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//        Class clazz = manager.getClass();
//        String imei2 = "";
//        String imei1 = "";
//        try {
//            Method getImei111 = clazz.getDeclaredMethod("getImei", int.class);
//            imei1 = (String) getImei111.invoke(manager, 0);
//            imei2 = (String) getImei111.invoke(manager, 1);
//            Logs.Debug("CPU ==" + "NEW2" + " IMEI1 ==" + imei1 + imei2);
//            com.example.mylib.LibUtils.Tools.msgbox(context, "CPU ==" + "NEW2" + " IMEI1 ==" + imei1 + imei2);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return imei2;
//    }

    public static String getMac()
    {
        String macSerial = null;
        String str = "";

        try
        {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str;)
            {
                str = input.readLine();
                if (str != null)
                {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
//            macSerial = "122222111";
            // 赋予默认值
            ex.printStackTrace();
        }
        return macSerial;
    }

    public static String getImei(Context context,int index){
        String imei = "";
        TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        Class clazz = manager.getClass();
        try {
            Method getImei = clazz.getDeclaredMethod("getImei",int.class);
            imei  = (String) getImei.invoke(manager,index);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return imei ;
    }

    /** 判断sd卡是否存在
     *
     */
    public static boolean isHaveSdCard() {
        boolean sdCardExist = Environment.MEDIA_MOUNTED
                .equals(Environment.getExternalStorageState());
        return sdCardExist;

    }

    public static Boolean GetPreferencesBoolean(Context context,String name,boolean defaultValue) {
        SharedPreferences preferences = context.getSharedPreferences("jinye_pre",Context.MODE_WORLD_READABLE);
        return preferences.getBoolean(name, defaultValue);

    }
    public static String currentVersion(Context context, String appPackage) {
        String ver = null;
        try {
            appPackage = context.getPackageName();
            ver = context.getPackageManager().getPackageInfo(appPackage, 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ver;
    }
    public static void PutPreferencesBoolean(Context context,String name,Boolean value)
    {
        SharedPreferences preferences = context.getSharedPreferences("jinye_pre",Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(name, value);
        //提交更改
        editor.commit ();
    }
    /*
    系统短信
     */
    public static void sendSmsWithBody(Context context, String number, String body) {
        Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
        sendIntent.setData(Uri.parse("smsto:" + number));
        sendIntent.putExtra("sms_body", body);
        context.startActivity(sendIntent);
    }

    /**
     * 关闭软键盘
     */
    public static void closeKeyboard(Activity context){

        InputMethodManager imm =  (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);

        if(imm != null) {
            imm.hideSoftInputFromWindow(context.getWindow().getDecorView().getWindowToken(), 0);
        }
    }
        /*
        验证是不是手机号码
         */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^1[2345678]\\d{9}$");

        Matcher m = p.matcher(mobiles);
        return m.matches();
    }
    /*
    系统的分享文字
     */
    public static void systemShareText(Context mContext,String word){
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, word);
        shareIntent.setType("text/plain");
        //设置分享列表的标题，并且每次都显示分享列表
        mContext.startActivity(Intent.createChooser(shareIntent, "分享到"));

//        UMUtile.showShare(mContext,word,onclick);
    }

    /**
     *确定取消()对话框
     * @param context
     * @param msg
     * @param positive 事件
     */
    public static void simpleDialog(Context context, String title,String msg, DialogInterface.OnClickListener positive) {
        new AlertDialog.Builder((context)).setTitle(title).setMessage(msg)
                .setPositiveButton("确定", positive).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).show();
    }

    /*
 调用拨打页面
  */
    public static void callPhone(Activity activity,String phone){

        Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    /*

   */
    public static String getStringNoNULL(String phone){
        if (TextUtils.isEmpty(phone)){
            return "";
        }
        return phone;
    }


    public  static String getLocation(Location location,Activity mContext) {
        String mlatitude = location.getLatitude()+"";
        String  mlongitude = location.getLongitude()+"";
        Geocoder geocoder=new Geocoder(mContext);
        try{
            // 2：通过经纬度来获取地址，由于地址可能有多个，这和经纬度的精确度有关，本例限制最大返回数为5
            final List<Address> list = geocoder.getFromLocation(Double.parseDouble(mlatitude),Double.parseDouble(mlongitude), 5);
//            if(list != null){
//                for(int i = 0 ; i < list.size() ; i ++){
//                    Address address = list.get(i);
//                    Log.v("MainActivity","------"+"(" + i + ") location at " +address.getLongitude() + "," +address.getLatitude()  +":" + address.getLocality());
//                }
//            }
            if (list==null){
                return null;
            }
            if (list.size()>1){
                Address address = list.get(1);

                return address.getLocality()+"";
            }else {
                Address address = list.get(0);
                return address.getLocality()+"";
            }
        }catch(Exception e){
            Log.e("WEI","Error : " + e.toString());
            return null;
        }
    }


    /**
     * 判断是否有可用的内容提供器
     * @return 不存在返回null
     */
    private static String judgeProvider(LocationManager locationManager) {
        List<String> prodiverlist = locationManager.getProviders(true);
        if(prodiverlist.contains(LocationManager.NETWORK_PROVIDER)){
            return LocationManager.NETWORK_PROVIDER;
        }else if(prodiverlist.contains(LocationManager.GPS_PROVIDER)) {
            return LocationManager.GPS_PROVIDER;
        }
        return null;
    }

    /**
     * 将图片转换成Base64编码的字符串
     * @param path
     * @return base64编码的字符串
     */

    public static String imageToBase64(String path) throws IOException {
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.DEFAULT);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return "data:image/gif;base64,"+result;
    }

    public static String buildTransaction(String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }



           /*
           获得id
            */
    @SuppressLint("MissingPermission")
    public static String getIMEI(Context context) {
        String imei;
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();
        } catch (Exception e) {
            imei = "";
        }
        return imei;
    }

    /*
    获得当前进程
     */
   public static String getCurProcessName(Context context) {
       int pid = android.os.Process.myPid();
       ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

       for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()){
            if (appProcess.pid == pid)  {
                return appProcess.processName;
            }
       }
       return null;
    }

    /**
     *
     * @param f          数字
     * @param formatstring                      格式 "#.00" ，几个0代表几位
     */
    public static double xiaoshudian(double f,String formatstring) {
        DecimalFormat df = new DecimalFormat(formatstring);

        return Double.parseDouble(df.format(f));

    }

    public static void hideKeyboard(Context mcontext,ViewGroup view){
        view.requestFocus();
        InputMethodManager im= (InputMethodManager) mcontext.getSystemService(Context.INPUT_METHOD_SERVICE);
        try{
            im.hideSoftInputFromWindow(view.getWindowToken(),0);

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void showKeyboard(Context mcontext,View view){
        InputMethodManager im= (InputMethodManager) mcontext.getSystemService(Context.INPUT_METHOD_SERVICE);
        im.showSoftInput(view,0);
    }

    public static void toast(Context mcontext,String text){
        Toast.makeText(mcontext,text, Toast.LENGTH_SHORT).show();
    }

}
